package com.cstz.ydshop.common.utils;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.cstz.sms.SubmitReq;
import com.cstz.sms.SubmitRsp;

public class SimSmsUtil {

	private static final Logger log = Logger.getLogger(SimSmsUtil.class);
	
	private static String url = "http://112.35.1.155:1992/sms/tmpsubmit";
	
	static{
		//APP_KEY = PropertyUtils.getSimAppKey();
		//APP_SECRET = PropertyUtils.getSimAppSecret();
	}
	
	public static boolean sendSms(String mobile,String content){
		boolean result = false;
		int count = 1;
		while(true){
			try{
				if(count>3){
					log.warn("发送短信重试次数超过3次，不再发送.........");
					break;
				}
				boolean flag = sendSms(mobile,content,count);
				if(flag){
					result = true;
					break;
				}
			}catch(Exception e){
				log.error("发送短信失败",e);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
			
			count ++;
		}
		
		return result;
	}
	
	public static boolean sendSms(String mobile,String content,int count){
		boolean flag = false;
		
		log.info("第"+count+"次发送短信,mobile:"+mobile+",content:"+content);
		SubmitReq req = new SubmitReq();
		req.setMobiles(mobile);
		req.setParams("[\""+content+"\"]");
		req.genMac(content);
		
		String jsonStr = JSONUtils.beanToJson(req);
		log.info("json:"+jsonStr);
		
		String base64Str = null;
		try {
			base64Str = Base64.encodeBase64String(jsonStr.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		log.info("base64:"+base64Str);
		String responseStr = HttpClientUtils.getResponseByPostBody(url,base64Str,null);
		log.info(mobile+"返回参数:"+responseStr);
		
		SubmitRsp result = new SubmitRsp();
		result = (SubmitRsp)JSONUtils.jsonToBean(responseStr, result);
		if(result.isSuccess()){
			flag  = true;
		}
		
		
		return flag;
	}
	
	
	public static void main(String[] args) {
		sendSms("18373191997","123321");
		
	}
}
